package com.young.android.view;

import java.util.ArrayList;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.young.android.R;
import com.young.android.business.ItemBusi;
import com.young.android.common.BaseActivity;
import com.young.android.common.Const;
import com.young.android.entity.Item;

public class ContentActivity extends BaseActivity {

    ArrayList<Item> feed;
    int position;

    WebView mWebView;
    ImageButton mNextImgBtn;
    ImageButton mPreImgBtn;
    TextView mPageInfoText;

    String pageInfo;

    Bundle bundle;

    private GestureDetector gestureDetector= new GestureDetector(new WebViewGestureDetector());;
    View.OnTouchListener gestureListener;

    @Override
    protected void init() {
        // TODO Auto-generated method stub
        setContentView(R.layout.content_view);

        bundle = getIntent().getExtras();
        feed = RSSFeedRead.getFeed();
        position = bundle.getInt("position");

        String contentURL;

        mWebView = (WebView) findViewById(R.id.content_webview);

        mWebView.getSettings().setDefaultTextEncodingName("utf-8");// 调整编码
        mWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);// 自适应宽度
        contentURL = "http://mrss.3g.qq.com:8081/?scid=0&type=page&url=" + feed.get(position).link
                + "&width=320";
        mWebView.loadUrl(contentURL);

        mPageInfoText = (TextView) findViewById(R.id.page_info_text);
        pageInfo = "(" + (position + 1) + "/" + feed.size() + ")";
        mPageInfoText.setText(bundle.getString("rssName") + pageInfo);

        mNextImgBtn = (ImageButton) findViewById(R.id.next_page);
        mNextImgBtn.setOnClickListener(new nextPositionListener());

        mPreImgBtn = (ImageButton) findViewById(R.id.pre_page);
        checkButtonVisible(position);
        mPreImgBtn.setOnClickListener(new prePositionListener());

        // 触摸监听
        mWebView.setOnTouchListener(wbTouch);

        // 加载事件监听
        mWebView.setWebViewClient(wvc);
        mWebView.setWebChromeClient(wbc);
    }
    
    /**
     * 页面加载完成及开始监听器
     */
    private WebViewClient wvc = new WebViewClient() {

        ProgressBar pg = null;
        ImageView loadAni;
        FrameLayout loadingFrame;

        @Override
        public void onPageFinished(WebView view, String url) {
            // 结束不可见
            pg.setVisibility(View.GONE);
            loadingFrame.setVisibility(View.GONE);
            mWebView.setVisibility(View.VISIBLE);

            // 更改条目状态
            ItemBusi.setItemState(Const.ITEM_READ, feed.get(position));
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mWebView.setVisibility(View.GONE);
            pg = (ProgressBar) findViewById(R.id.webview_progress);
            pg.setVisibility(View.VISIBLE);
            // 加载载入动画
            loadingFrame = (FrameLayout) findViewById(R.id.loading_frame);
            loadingFrame.setVisibility(View.VISIBLE);
            loadAni = (ImageView) findViewById(R.id.loading_ani);
            Animation ani = AnimationUtils.loadAnimation(ContentActivity.this, R.anim.loading);
            loadAni.startAnimation(ani);
        }

    };

    private WebChromeClient wbc = new WebChromeClient() {
        ProgressBar pg = null;

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // TODO Auto-generated method stub
            pg = (ProgressBar) findViewById(R.id.webview_progress);
            pg.setProgress(newProgress);
        }

    };

    private View.OnTouchListener wbTouch = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    };

    /**
     * WebViewGestureDetector 手势操作类
     * 
     * @author Young
     */
    public class WebViewGestureDetector extends SimpleOnGestureListener {
    
        // 手势范围常量
        private static final int SWIPE_MIN_DISTANCE = 120;
        private static final int SWIPE_MAX_OFF_PATH = 250;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            // TODO Auto-generated method stub
            // 竖向操作过大，忽略
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            // 右到左
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                nextPosition();
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                prePosition();
            }
            return false;
        }
    
    }

    private class nextPositionListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            nextPosition();
        }

    }

    private class prePositionListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            prePosition();
        }

    }

    private void checkButtonVisible(int position) {
        if (position == 0) {
            mPreImgBtn.setVisibility(View.GONE);
        } else {
            mPreImgBtn.setVisibility(View.VISIBLE);
        }
        if (position == feed.size() - 1) {
            mNextImgBtn.setVisibility(View.GONE);
        } else {
            mNextImgBtn.setVisibility(View.VISIBLE);
        }
    }

    private void nextPosition() {
        // 判断是否可往后
        if (position == feed.size() - 1) {
            return;
        }
        String contentURL = "http://mrss.3g.qq.com:8081/?scid=0&type=page&url="
                + feed.get(++position).link + "&width=320";
        mWebView.loadUrl(contentURL);

        pageInfo = "(" + (position + 1) + "/" + feed.size() + ")";
        mPageInfoText.setText(bundle.getString("rssName") + pageInfo);
        checkButtonVisible(position);
    }

    private void prePosition() {
        // 判断是否可往前
        if (position == 0) {
            return;
        }
        String contentURL = "http://mrss.3g.qq.com:8081/?scid=0&type=page&url="
                + feed.get(--position).link + "&width=320";
        mWebView.loadUrl(contentURL);
        pageInfo = "(" + (position + 1) + "/" + feed.size() + ")";
        mPageInfoText.setText(bundle.getString("rssName") + pageInfo);
        checkButtonVisible(position);
    }

}
